﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form21 : Form
    {
        public Form21()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        static object apple=new object();
        int maxApple = 10;
        int produceApple = 0;
        int consumeApple = 0;
        bool flag=false;
        Thread tProduce=null;
        Thread tConsume=null;

        public void Produce() {
            while (!flag) {
                lock (apple) {
                    for (int i = 1; i <= maxApple; i++) { 
                         this.listBox1.Items.Add(i.ToString());
                        produceApple++;
                        this.label4.Text=produceApple.ToString();
                        if (i == produceApple) {
                            this.listBox1.Items.Add("苹果生产完了");
                            flag= true;
                        }
                        Thread.Sleep(500);
                        Monitor.Pulse(apple);
                        Monitor.Wait(apple);
                    }
                }
            }
        }

        public void Consume() {
            while (true) {
                lock (apple) {
                    consumeApple = consumeApple + produceApple;
                    this.listBox3.Items.Add(consumeApple.ToString());
                    produceApple--;
                    this.label4.Text=produceApple.ToString() ;
                    if (flag) {
                        this.listBox3.Items.Add("苹果卖完了");
                    }
                    Thread.Sleep(500);
                    Monitor.Pulse(apple);
                    Monitor.Wait(apple);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            tProduce = new Thread(new ThreadStart(Produce));
            tConsume=new Thread(new ThreadStart(Consume));
            tProduce.Start();
            tConsume.Start();
            button1.Enabled= false; 
            button2.Enabled= true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            tProduce.Abort();
            tConsume.Abort();
            button1.Enabled = true;
            button2.Enabled = false;
            this.listBox1.Items.Clear();
            this.listBox3.Items.Clear();
            this.label4.Text = "0";
            flag = false;
            produceApple= 0;
            consumeApple= 0;
        }
    }
}
